<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" disabled placeholder="请输入单据编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="desFlowType">
              <j-dict-select-tag
                type="list"
                v-model="model.desFlowType"
                dictCode="constract_des_flow_type"
                placeholder="请选择审批流程"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>

        </a-row>

        <a-row>
        <a-col :span="8">
          <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
<!--                          <tsl-erp-customer v-model="model.customerId" @handlerok="changeCustomer"  :disabled="formDisabled"> </tsl-erp-customer>-->
<!--            <j-dict-select-tag type="list"  dictCode="erp_customer,name,id" v-model="model.customerId" :disabled="formDisabled" @change="changeCustomer" placeholder="请选择客户" />-->
          <a-input v-model="model.customerId_dictText" :disabled="formDisabled" @click="handleClick"> </a-input>
            <TslSelectCustomer ref="selectCustomer" @selectOk="handleSelect" ></TslSelectCustomer>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="业务员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesman">
                          <j-dict-select-tag v-model="model.salesman" dictCode="tsl_hr_employee_info,employee_name,id," placeholder="请输入业务员" disabled></j-dict-select-tag>
<!--            <j-select-user-by-dep-v2 v-model="model.salesman" :disabled="formDisabled" disabled :multi="true" />-->
          </a-form-model-item>
        </a-col>
          <a-col :span="8">
            <a-form-model-item label="材料价格执行表" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bussMaterialPriceId">
              <!--              <tsl-erp-customer v-model="model.customerId" @handlerok="changeCustomer"  :disabled="formDisabled"> </tsl-erp-customer>-->
<!--              <j-dict-select-tag type="list"  dictCode="buss_material_price,code,id" v-model="model.bussMaterialPriceId"  placeholder="请选择原料价格执行表" />-->
              <j-search-select-tag
                placeholder="请选择材料价格执行表"
                v-model="model.bussMaterialPriceId"
                :disabled="formDisabled"
                :dictOptions="dictOptions">
              </j-search-select-tag>
            </a-form-model-item>
          </a-col>
          </a-row>
<!--        <a-tabs v-bind="$attrs" :disabled="false" :default-active-key="tabkeys[0]" @change="handleChangeTabs">-->
<!--          <a-tab-pane tab="合同评审说明信息" :key="tabkeys[0]" :forceRender="true">-->
            <a-row justify="start">
              <a-col :span="24">
                <a-form-model-item label="一、配方要求 " prop="formulaReq">
                  <a-textarea
                   :disabled="formDisabled"
                    v-model="model.formulaReq"
                    :rows="5"
                    allow-clear
                    showCount
                    placeholder="请输入配方要求"
                  ></a-textarea>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row justify="start">
              <a-col :span="36">
                <a-form-model-item label="二、包装要求" prop="packReq">
                  <a-textarea
                   :disabled="formDisabled"
                    v-model="model.packReq"
                    :rows="10"
                    allow-clear
                    showCount
                    placeholder="请输入包装要求"
                  ></a-textarea>
                </a-form-model-item>
              </a-col>
            </a-row>
            <h4>三、价格条款:</h4>
            <a-row>
              <a-col :span="5">
                <a-form-model-item label="订货数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="weight">
                  <a-row>
                    <a-col :span="16">

                      <a-input-number v-model="model.weight" placeholder="请输入数量" style="width: 100%"  :disabled="formDisabled"/>
                    </a-col>
                    <a-col :span="8">
                      <j-dict-select-tag
                        type="list"
                         :disabled="formDisabled"
                        v-model="model.weightUnit"
                        dictCode="zl_unit"
                        placeholder="请选择单位"
                      />
                    </a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>
              <a-col :span="5">
                <a-form-model-item label="柜数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cabinetCount">
<!--                  <a-row>
                    <a-col :span="12">-->
                      <a-input v-model="model.cabinetCount" placeholder="请输入柜数"  :disabled="formDisabled"></a-input>
<!--                    </a-col>
                    <a-col :span="12">
                      <a-input v-model="model.extra" placeholder="请输入单位"  :disabled="formDisabled"></a-input>
                    </a-col>
                  </a-row>-->
                </a-form-model-item>
              </a-col>
              <a-col :span="4">
                <a-form-model-item
                  label="成交方式"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="transactionMethod"
                >
                  <a-input v-model="model.transactionMethod" placeholder="请输入成交方式"  :disabled="formDisabled"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="5">
                <a-form-model-item label="发货港" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shipPort">
                  <a-input v-model="model.shipPort" placeholder="请输入发货港"  :disabled="formDisabled"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="5">
                <a-form-model-item label="目的港" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="destPort">
                  <a-input v-model="model.destPort" placeholder="请输入目的港"  :disabled="formDisabled"></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row>
                <h4 >四、付款方式:</h4>
              <a-col :span="6">
                <a-form-model-item label="财务备录" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="financeRemark">
                  <a-input v-model="model.financeRemark" placeholder="请输入财务备录"  :disabled="formDisabled"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="付款方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payMethod">
                  <a-input v-model="model.payMethod" placeholder="请输入付款方式"  :disabled="formDisabled"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item
                  label="到货后付全款天数"
                  :labelCol="labelColLong"
                  :wrapperCol="wrapperColLong"
                  prop="daysArrival"

                >
                  <a-input-number
                   :disabled="formDisabled"
                    v-model="model.daysArrival"
                    placeholder="请输入到货后付全款天数"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row >
              <a-col :span="12">
                <a-row>
                  <a-col :span="4">
                    <h4>五、交货期:</h4>
                  </a-col>
                  <a-col :span="20">
                    <a-form-model-item prop="deliveryTime">
                      <a-input v-model="model.deliveryTime" placeholder="请输入交货期"  :disabled="formDisabled"></a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="4">
                    <h4>六、溢短装:</h4>
                  </a-col>
                  <a-col :span="20">
                    <a-form-model-item prop="overflowShort">
                      <a-input v-model="model.overflowShort" placeholder="请输入溢短装"  :disabled="formDisabled"></a-input>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row>
                  <a-col :span="4">
                    <h4>七、客户类型:</h4>
                  </a-col>
                  <a-col :span="20">
                    <a-form-model-item prop="customer">
<!--                      <a-input v-model="model.customer" placeholder="请输入客户类型"  :disabled="formDisabled"></a-input>-->

                      <j-dict-select-tag type="list"  dictCode="customer_category" v-model="model.customer"  :disabled="formDisabled" placeholder="请选择客户类型" />
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>

            </a-row>

        <a-row>
          <a-col :span="12">
            <h4>八、附件列表</h4>
            <j-vxe-table
              keep-source
              :ref="refKeys[0]"
              :loading="bussContractReviewDesFilesTable.loading"
              :columns="bussContractReviewDesFilesTable.columns"
              :dataSource="bussContractReviewDesFilesTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="true"
              :toolbar="true"
            >
              <template v-slot:action="props">
                <a @click="handlePreviewFile(props)">预览</a>
              </template>
            </j-vxe-table>
          </a-col>
        </a-row>
<!--          </a-tab-pane>
          <a-tab-pane tab="状态履历修改" :key="tabkeys[1]" >
            <tsl-history dataTable="buss_contract_review_des" :dataId="model.id"></tsl-history>
          </a-tab-pane>
        </a-tabs>-->
      </a-form-model>
    </j-form-container>
<!--    <a-card>
      <a-row>
        <a-col :span="6">
          <a-form-model-item label="制单人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createBy">
            <a-input disabled v-model="model.createBy_dictText" placeholder="请输入制单人"></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="制单部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sysOrgCode">
            <j-select-depart disabled v-model="model.departIds" :multi="true" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-model-item label="制单日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
            <a-input disabled v-model="model.createTime" placeholder="请输入制单日期"></a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-card>-->
  </a-spin>
</template>

<script>
import {getAction, httpAction, putAction} from '@/api/manage'
import { FilePreview } from '@/utils/tslCommon'
//获取登录用户的信息
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import TslErpCustomer from '@comp/tsl/TslErpCustomer.vue'
import TslHistory from '@comp/tsl/TslHistory.vue'
import store from '@/store'
import Vue from "vue";
import TslSelectCustomer from '@comp/tsl/modules/TslSelectCustomer.vue'
export default {
  name: 'BussContractReviewDesForm',
  mixins: [JVxeTableModelMixin],
  components: {
    TslSelectCustomer,
    JFormContainer,
    TslErpCustomer,
    TslHistory
  },
  data() {
    return {
      tabkeys: ['info', 'uphistorys'],
      labelColLong: {
        xs: { span: 24 },
        sm: { span:5 },
        style: 'width: 55%;',
      },
      wrapperColLong: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
      labelCol2Column: {
        xs: { span: 24 },
        sm: { span: 3 },
        style: 'width: 20%;',
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        style: 'width: 32%;',
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        desFlowType: 1,
        weightUnit:1,
      },
      dictOptions:[],
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        code: [{ required: true, message: '请输入单据编号!' }],
        desFlowType: [{ required: true, message: '请选择流程!' }],
        weight: [{ required: true, message: '请输入订货数量!' }],
        weightUnit: [{ required: true, message: '请选择单位!' }],
        bussMaterialPriceId: [{ required: true, message: '请选择材料价格执行表!' }],
        customerId: [{ required: true, message: '请选择客户信息!' }],
      },
      refKeys: ['bussContractReviewDesFiles', 'history'],
      tableKeys: ['bussContractReviewDesFiles'],
      activeKey: 'bussContractReviewDesFiles',
      // 合同评审说明关联文件
      bussContractReviewDesFilesTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '附件',
            key: 'filePath',
            type: JVXETypes.file,
            token: true,
            disabled:this.formDisabled,
            responseName: 'message',
            placeholder: '请选择文件',
            defaultValue: '',
          },
          {
            title: '附件说明',
            key: 'fileDesc',
            type: JVXETypes.input,
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/business/bussContractReviewDes/add',
        edit: '/business/bussContractReviewDes/edit',
        queryById: '/business/bussContractReviewDes/queryById',
        bussContractReviewDesFiles: {
          list: '/business/bussContractReviewDes/queryBussContractReviewDesFilesByMainId',
        },
        price:'/procurement/materialPriceApproval/list'
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    if (this.customFormData != null && this.customFormData.id) {
      this.model = this.customFormData
      this.editAfter() //现在子表内容需要
/*      let user = store.getters.userInfo
      if (!this.model.createBy) {

        this.model.createBy_dictText = user.realname
        this.model.departIds = user.departIds
        const now = new Date()
        this.model.createTime = this.formatDate(now)
        // this.model.salesman=user.username
      }*/

      if(!this.model.weightUnit){
        this.model.weightUnit=1
      }

    }

    getAction(this.url.price,{pageSize:-1,order:'desc',column: 'createTime',searchModel:4}).then((res) => {
      res.result.records.forEach((item) => {

        this.dictOptions.push({text:item.executeCode,value:item.id})
        // 设置默认值为第一条记录
        if (this.dictOptions.length > 0) {
          this.model.bussMaterialPriceId = this.dictOptions[0].value; // 设置为第一条记录的 ID
        }
      })

    })

  },
  methods: {
    handleSelect(row){
      console.log("21313",row)
      this.model.customerId=row[0].id
      Vue.set(this.model,'customerId_dictText',row[0].name)
      this.changeCustomer()
      console.log("dddd",this.model)
    },
    handleClick(){
      console.log("abc")
      this.$nextTick(()=>{
        this.$refs.selectCustomer.add()
      })
    },
    request(formData) {
      let url = this.url.add, method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }else{
        formData.documentType=1
        formData.salesType=1
        formData.contractBusinessType=1
      }
      this.confirmLoading = true

      httpAction(url, formData, method).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok')
          this.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    changeCustomer() {
      getAction('/business/bussContractReviewDes/querySalesman', { id: this.model.customerId }).then((res) => {
        console.log(res)
        if (res.success) {
          // this.model.salesman = res.result.salesmanId
          // this.model.customer = res.result.category

          Vue.set(this.model, 'salesman', res.result.salesman)
          Vue.set(this.model, 'salesmanName', res.result.salesmanName)
          Vue.set(this.model, 'customer', res.result.category)
/*          let type = res.result.type
          if (type && type.name === '国内/OEM') {
            this.model.desFlowType = 2
          }
          if (type && type.name === '国贸') {
            this.model.desFlowType = 1
          }*/
        } else {
        }
      })
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，使用padStart方法补齐两位数
      const day = String(date.getDate()).padStart(2, '0') // 日期补齐两位数
      const hours = String(date.getHours()).padStart(2, '0') // 小时补齐两位数
      const minutes = String(date.getMinutes()).padStart(2, '0') // 分钟补齐两位数
      const seconds = String(date.getSeconds()).padStart(2, '0') // 秒补齐两位数

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    handlePreviewFile(row) {
      console.log(row);
      let filePath = row.row.filePath
      FilePreview(filePath);
    },
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/contract_review_desc'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result
          this.$forceUpdate();
        }
      })
    },
    addBefore() {
      this.bussContractReviewDesFilesTable.dataSource = []
      this.getSequenceNum()
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      console.log("babbs",this.model)
      console.log("1233321")
      if(this.model.salesman!=null){
        getAction("/business/bussContractReviewDes/getSalesmanDict",{id:this.model.salesman}).then(res=>{
          if (res.success) {
            this.model.salesman_dictText=res.result
          }
        })
      }
      if (this.model.customerId!=null){
        getAction("/business/bussContractReviewDes/getCustomerIdDict",{id:this.model.customerId}).then(res=>{
          if (res.success) {
            this.model.customerId_dictText=res.result
          }
        })
      }
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.bussContractReviewDesFiles.list, params, this.bussContractReviewDesFilesTable)
      }
    },
    copy(record){
      this.model=Object.assign({},record);
      this.model.id=undefined;
      this.model.createBy=undefined;
      this.model.createTime=undefined;
      this.model.updateBy=undefined;
      this.model.updateTime=undefined;
      this.model.sysOrgCode=undefined;
      this.model.code="";
      this.getSequenceNum();
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        bussContractReviewDesFilesList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
  },
}
</script>

<style scoped>
.custom-card-title {
  font-size: 16px;
  font-weight: bold;
}
.ant-modal {
  width: 100vw !important;
  max-width: 100vw !important;
  top: 0;
  padding-bottom: 0;
}

.ant-modal-body {
  height: calc(100vh - 55px - 53px);
  overflow-y: auto;
}
</style>
